import { useEffect, useState, useRef } from 'react';
import { Button, Card, Form, message, Popconfirm, Space } from 'antd';
import { ProForm, ProFormDatePicker } from '@ant-design/pro-components';
import { resetSyncDataApi, tongBuPositionsApi } from '@/api';
import { isSuccess } from '@/utils';
import { useRequest } from 'ahooks';
import dayjs from 'dayjs';

// 表单样式
const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};

// const shiBa = dayjs().format('YYYY-MM-DD 18:00:00');
const shiBa = dayjs().format('2025-03-29 24:00:00');
const lingChen = dayjs().format('YYYY-MM-DD 24:00:00');
export default function SyncCangWei() {
  const [loadingSync, setLoadingSync] = useState(false);
  const formRef: any = useRef('');
  useEffect(() => {
    initData();
  }, []);

  // 初始化数据
  const initData = () => {
    formRef.current.setFieldsValue({ date: '2025-03-12' });
  };

  // 提交
  const submit = async () => {
    let formatData = await formRef?.current?.validateFieldsReturnFormatValue();
    const { date } = formatData;
    await tongBu({ date });
  };

  // 同步仓位
  const tongBu = async (params = {}) => {
    console.log('params:同步 ', params);
    setLoadingSync(true);
    const res: any = await tongBuPositionsApi(params);
    setLoadingSync(false);
    console.log('res: 同步', res?.data);
    if (!isSuccess(res)) return;
    message.success('同步成功');
  };

  // 重置仓位
  const { loading, run: resetSyncData } = useRequest(async () => resetSyncDataApi(), {
    manual: true,
    onSuccess: (res) => {
      console.log('res: 重置', res?.data);
    },
  });

  return (
    <div>
      <Card>
        <p>同步历史仓位</p>
        <ProForm
          title="新建表单"
          formRef={formRef}
          layout="horizontal"
          {...formItemLayout}
          onFinish={submit}
        >
          <ProFormDatePicker name="date" label="日期" />
        </ProForm>{' '}
        <br />
        <Space>
          <Button loading={loadingSync} onClick={() => tongBu({ date: lingChen })}>
            凌晨同步
          </Button>
          <Button loading={loadingSync} onClick={() => tongBu({ date: shiBa })}>
            18点同步
          </Button>
          <Popconfirm title="确认重置同步信息吗？" onConfirm={resetSyncData}>
            <Button loading={loading} danger>
              重置同步信息
            </Button>
          </Popconfirm>
        </Space>
      </Card>
      <br />
    </div>
  );
}
